from socket import *
from multiprocessing import Process
import re
import sys

# 设置静态文件根目录
HTML_ROOT_DIR = "./html"
WSGI_PYTHON_DIR = '/Users/rainhowchan/VscodeProject/python_p/helloworld/src/web/wsgi_package'


class HttpServer:

	def __init__(self):
		sys.path.insert(1, WSGI_PYTHON_DIR)
		self.serverSocket = socket(AF_INET, SOCK_STREAM)
		self.serverSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
		self.serverSocket.bind(('', 8080))
		self.serverSocket.listen(128)
		self.responseBody = None
		self.responseHeaders = "Server: My Server\r\n"

	def accept(self):
		return self.serverSocket.accept()

	def startResponse(self, status, headers):
		"""
		status = '200 OK'
		headers = [
			('Content-type', 'text/html;charset=utf-8')
		]
		"""
		responseHeaders = "HTTP/1.1 " + status + "\r\n"
		for header in headers:
			responseHeaders += "%s: %s\r\n" % header
		self.responseHeaders = responseHeaders

	def handler(self, clientSocket):
		"""处理客户端请求"""
		responseHeaders = "Server: My Server\r\n"
		# 获取客户端请求数据
		requestData = clientSocket.recv(1024)
		requestLines = requestData.splitlines()
		for line in requestLines:
			print(line)
		if len(requestLines):
			requestStartLine = requestLines[0]
		else:
			return
		# 提取用户请求的文件名 GET / HTTP/1.1
		requestRaw = re.match(r"(\w+)\s+(/[^\s]*)\s", requestStartLine.decode('utf-8'))
		method = requestRaw.group(1)
		fileName = requestRaw.group(2)

		responseStartLine = "HTTP/1.1 200 OK\r\n"

		if fileName.endswith('.py'):
			print(fileName[1:-3])
			print(sys.path)
			m = __import__(fileName[1:-3])  # 动态导入模块
			env = {
				"PATH_INFO": fileName,
				"Method": method
			}
			self.responseBody = m.application(env, self.startResponse)
			response = self.responseHeaders + '\r\n' + self.responseBody

		else:
			if '/' == fileName:
				fileName = '/index.html'
				# 打开文件 读取内容
			try:
				file = open(HTML_ROOT_DIR + fileName, 'rb')
			except IOError:
				responseStartLine = 'HTTP/1.1 404 Not Found\r\n'
				self.responseBody = 'the file is not found'
			else:
				fileData = file.read()
				file.close()
				# 构造响应数据
				self.responseBody = fileData.decode('utf-8')

			response = responseStartLine + self.responseHeaders + "\r\n" + self.responseBody

		print(self.responseBody)
		# 向客户端返回响应数据
		clientSocket.send(bytes(response, 'utf-8'))
		# 关闭客户端
		clientSocket.close()


if __name__ == '__main__':
	httpServer = HttpServer()


while True:
	clientSocket, clientAddress = httpServer.accept()
	print("[%s, %s] 用户连接上了" % clientAddress)
	# 拷贝了一份到子进程中去了
	handleClientProcess = Process(target=httpServer.handler, args=(clientSocket, ))
	handleClientProcess.start()
	clientSocket.close()
